package com.ccyang;

import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: yangjinpeng
 * @date: 2018-12-23
 * @description: 终止操作
 */
public class StreamDemo4 {

    public static void main(String[] args) {

        String str = "my name is 0007";

        // 使用并行流
        str.chars().parallel().forEach(i -> System.out.print((char)i));
        System.out.println();

        // 使用forEachOrder保证顺序
        str.chars().parallel().forEachOrdered(i -> System.out.print((char)i  ));
        System.out.println();

        // 收集到list
        List<String> list = Stream.of(str.split(" ")).collect(Collectors.toList());
        System.out.println(list );

        // 使用reduce 拼接字符串
        Optional<String> letters = Stream.of(str.split(" ")).reduce((s1, s2) -> s1 + "|" + s2);
        System.out.println(letters.orElse(""));

        // 带初始值的reduce
        String reduce = Stream.of(str.split(" ")).reduce("", (s1, s2) -> s1 + "|" + s2);
        System.out.println(reduce);

        // 计算所有单词总长度
        Integer length = Stream.of(str.split(" ")).map(s -> s.length()).reduce(0, (s1, s2) -> s1 + s2);
        System.out.println(length);

        // max的使用
        Optional<String> max = Stream.of(str.split(" ")).max((s1, s2) -> s1.length() - s2.length());
        System.out.println(max.get());

        // count的使用
        long count = Stream.of(str.split(" ")).count();
        System.out.println(count);

        // --------短路操作---------
        // findFirst 的使用
        OptionalInt first = new Random().ints().limit(10).findFirst();
        System.out.println(first.getAsInt());

        OptionalInt any = new Random().ints().limit(10).findAny();
        System.out.println(any.getAsInt());

        // 所有值匹配
        boolean b = Stream.of(str.split(" ")).allMatch(i -> i.length() > 3);
        System.out.println(b);
        boolean b2 = Stream.of(str.split(" ")).allMatch(i -> i.length() > 1);
        System.out.println(b2);
    }

}
